<template>
  <el-row :gutter="20" class="random-panel">
    <el-col :xs="24" :sm="24" class="main-content">
      <RandomCharacter />
      <el-card class="panel-card">
        <template #header>
          <div class="card-header">
            <el-text class="mr5">{{ $t('message.random.selectStyle') }}</el-text>
            <el-input v-stop-comfy-events v-model="state.style.customize_name" :placeholder="$t('message.random.customizeName')" clearable
              class="full-width-input" />
          </div>
        </template>

        <div class="content-wrapper">
          <el-image :src="getProcessedImageUrl(state.style)"
            :preview-src-list="[getProcessedImageUrl(state.style)]" hide-on-click-modal class="preview-image-lg"
            fit="cover" />

          <el-row class="tag-input" :gutter="5">
            <el-col class="mb5" :span="24">
              <el-input v-stop-comfy-events v-model="state.style.tags" type="textarea" :rows="4" resize="none" />
            </el-col>
            <el-col class="mb5" :span="24">
              <el-rate v-model="state.style.rating" show-score :max="10" allow-half clearable
                score-template="{value} points" />
            </el-col>
            <el-col class="mb5" :span="24">
              <div style="display: flex;">
                <el-text class="mr5">{{ $t('message.random.favorite') }}:</el-text>
                <el-switch v-model="state.style.favorite" inline-prompt :active-text="$t('message.common.yes')"
                  :active-value="1" :inactive-value="0" :inactive-text="$t('message.common.no')" />
                <el-text class="mr5 ml10">{{ $t('message.random.disliked') }}:</el-text>
                <el-switch v-model="state.style.disliked" inline-prompt :active-value="1" :inactive-value="0"
                  :active-text="$t('message.common.yes')" :inactive-text="$t('message.common.no')" />
                <el-text class="ml10">{{ state.style.id }}</el-text>
              </div>
            </el-col>
          </el-row>
        </div>
        <template #footer>
          <el-space wrap>
            <el-button size="default" type="primary" @click="getCommonRandom('style')" icon="MagicStick">{{
              $t('message.random.randomStyle') }}</el-button>
            <el-button size="default" type="info" @click="handleMoreAction('style', 'update-item')" icon="Box">{{
              $t('message.random.applyChange') }}</el-button>
            <el-button size="default" type="danger" @click="handleClear('style')" icon="Delete">{{
              $t('message.common.clear') }}</el-button>
            <el-dropdown>
              <el-button size="default" type="success">{{ $t('message.random.moreAction')
              }}<el-icon><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleMoreAction('style', 'copy')">{{ $t('message.random.copyInfo')
                  }}</el-dropdown-item>
                  <el-dropdown-item @click="handleMoreAction('style', 'update-image')">{{
                    $t('message.random.replacePreview') }}</el-dropdown-item>
                  <el-dropdown-item @click="handleMoreAction('style', 'update-item')">{{
                    $t('message.random.applyChange') }}</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-popover placement="top" :width="470" trigger="hover">
              <template #reference>
                <el-button size="default" class="range-btn" type="primary">{{ state.random.style.value}}</el-button>
              </template>
              <div>
                <el-slider style="width:400px;margin-left: 20px;" :step="0.5" v-model="state.random.style.value" range
                  show-stops :min="0" :max="10" />
              </div>
            </el-popover>
            <el-button size="default" type="primary" icon="ele-ArrowLeft"
              @click="handleNextItem(state.style.id, 'style')"></el-button>
            <el-button size="default" type="primary" icon="ele-ArrowRight"
              @click="handlePrevItem(state.style.id, 'style')"></el-button>
          </el-space>
        </template>
      </el-card>
      <el-card class="panel-card">
        <template #header>
          <div class="card-header">
            <el-text class="mr5">{{ $t('message.random.selectCollect') }}</el-text>
            <el-input v-stop-comfy-events v-model="state.collect.customize_name" :placeholder="$t('message.random.customizeName')" clearable
              class="full-width-input" />
          </div>
        </template>

        <div class="content-wrapper">
          <el-image :src="getProcessedImageUrl(state.collect)"
            :preview-src-list="[getProcessedImageUrl(state.collect)]" hide-on-click-modal class="preview-image-lg"
            fit="cover" />
          <el-row class="tag-input" :gutter="5">
            <el-col class="mb5" :span="24">
              <el-input v-stop-comfy-events v-model="state.collect.tags" type="textarea" :rows="4" resize="none" />
            </el-col>
            <el-col class="mb5" :span="24">
              <el-rate v-model="state.collect.rating" show-score :max="10" allow-half clearable
                score-template="{value} points" />
            </el-col>
            <el-col class="mb5" :span="24">
              <div style="display: flex;">
                <el-text class="mr5">{{ $t('message.random.favorite') }}:</el-text>
                <el-switch v-model="state.collect.favorite" inline-prompt :active-text="$t('message.common.yes')"
                  :active-value="1" :inactive-value="0" :inactive-text="$t('message.common.no')" />
                <el-text class="mr5 ml10">{{ $t('message.random.disliked') }}:</el-text>
                <el-switch v-model="state.collect.disliked" inline-prompt :active-value="1" :inactive-value="0"
                  :active-text="$t('message.common.yes')" :inactive-text="$t('message.common.no')" />
                <el-text class="ml10">{{ state.collect.id }}</el-text>
              </div>
            </el-col>
          </el-row>
        </div>

        <template #footer>
          <el-space wrap>
            <el-button size="default" type="primary" @click="getCommonRandom('collect')" icon="MagicStick">{{
              $t('message.random.randomCollect') }} </el-button>
            <el-button size="default" type="info" @click="handleMoreAction('collect', 'update-item')" icon="Box">{{
              $t('message.random.applyChange') }}</el-button>
            <el-button size="default" type="danger" @click="handleClear('collect')" icon="Delete">{{
              $t('message.common.clear') }}</el-button>
            <el-dropdown>
              <el-button size="default" type="success">{{ $t('message.random.moreAction')
              }}<el-icon><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleMoreAction('collect', 'copy')">{{ $t('message.random.copyInfo')
                  }}</el-dropdown-item>
                  <el-dropdown-item @click="handleMoreAction('collect', 'update-image')">{{
                    $t('message.random.replacePreview') }}</el-dropdown-item>
                  <el-dropdown-item @click="handleMoreAction('collect', 'update-item')">{{
                    $t('message.random.applyChange') }}</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-popover placement="top" :width="470" trigger="hover">
              <template #reference>
                <el-button size="default" class="range-btn" type="primary">{{ state.random.collect.value
                }}</el-button>
              </template>
              <div>
                <el-slider style="width:400px;margin-left: 20px;" :step="0.5" v-model="state.random.collect.value" range
                  show-stops :min="0" :max="10" />
              </div>
            </el-popover>
            <el-button size="default" type="primary" icon="ele-ArrowLeft"
              @click="handleNextItem(state.collect.id, 'collect')"></el-button>
            <el-button size="default" type="primary" icon="ele-ArrowRight"
              @click="handlePrevItem(state.collect.id, 'collect')"></el-button>
          </el-space>
        </template>
      </el-card>

      <!-- 动作卡片 -->
      <el-card class="panel-card">
        <template #header>
          <div class="card-header">
            <el-text class="mr5">{{ $t('message.random.selectAction') }}</el-text>
            <el-input v-stop-comfy-events v-model="state.action.customize_name" :placeholder="$t('message.random.customizeName')" clearable
              class="full-width-input" />
          </div>
        </template>

        <div class="content-wrapper">
          <el-image :src="getProcessedImageUrl(state.action)"
            :preview-src-list="[getProcessedImageUrl(state.action)]" hide-on-click-modal class="preview-image-lg"
            fit="cover" />
          <el-row class="tag-input" :gutter="5">
            <el-col class="mb5" :span="24">
              <el-input v-stop-comfy-events v-model="state.action.tags" type="textarea" :rows="4" resize="none" />
            </el-col>
            <el-col class="mb5" :span="24">
              <el-rate v-model="state.action.rating" show-score :max="10" allow-half clearable
                score-template="{value} points" />
            </el-col>
            <el-col class="mb5" :span="24">
              <div style="display: flex;">
                <el-text class="mr5">{{ $t('message.random.favorite') }}:</el-text>
                <el-switch v-model="state.action.favorite" inline-prompt :active-text="$t('message.common.yes')"
                  :active-value="1" :inactive-value="0" :inactive-text="$t('message.common.no')" />
                <el-text class="mr5 ml10">{{ $t('message.random.disliked') }}:</el-text>
                <el-switch v-model="state.action.disliked" inline-prompt :active-value="1" :inactive-value="0"
                  :active-text="$t('message.common.yes')" :inactive-text="$t('message.common.no')" />
                <el-text class="ml10">{{ state.action.id }}</el-text>
              </div>
            </el-col>
          </el-row>
        </div>

        <template #footer>
          <el-space wrap>
            <el-button size="default" type="primary" @click="getCommonRandom('action')" icon="MagicStick">{{
              $t('message.random.randomAction') }} </el-button>
            <el-button size="default" type="info" @click="handleMoreAction('action', 'update-item')" icon="Box">{{
              $t('message.random.applyChange') }}</el-button>
            <el-button size="default" type="danger" @click="handleClear('action')" icon="Delete">{{
              $t('message.common.clear') }}</el-button>
            <el-dropdown>
              <el-button size="default" type="success">{{ $t('message.random.moreAction')
              }}<el-icon><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleMoreAction('action', 'copy')">{{ $t('message.random.copyInfo')
                  }}</el-dropdown-item>
                  <el-dropdown-item @click="handleMoreAction('action', 'update-image')">{{
                    $t('message.random.replacePreview') }}</el-dropdown-item>
                  <el-dropdown-item @click="handleMoreAction('action', 'update-item')">{{
                    $t('message.random.applyChange') }}</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-popover placement="top" :width="470" trigger="hover">
              <template #reference>
                <el-button size="default" class="range-btn" type="primary">{{ state.random.action.value
                }}</el-button>
              </template>
              <div>
                <el-slider style="width:400px;margin-left: 20px;" :step="0.5" v-model="state.random.action.value" range
                  show-stops :min="0" :max="10" />
              </div>
            </el-popover>
            <el-button size="default" type="primary" icon="ele-ArrowLeft"
              @click="handleNextItem(state.action.id, 'action')"></el-button>
            <el-button size="default" type="primary" icon="ele-ArrowRight"
              @click="handlePrevItem(state.action.id, 'action')"></el-button>
          </el-space>
        </template>
      </el-card>

      <!-- 随机标签生成器 -->
      <el-card class="panel-card">
        <div class="card-header">
          <el-text class="mr5">{{ $t('message.random.randomTag') }}</el-text>
          <el-text type="info">{{ $t('message.random.randomTagTip') }}</el-text>
        </div>
        <RandomTagGenerator :random="state.random" @tags-generated="handleRandomTagsGenerated" />
      </el-card>
      <el-card class="panel-card">
        <LoraLoader />
      </el-card>
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import { computed, defineAsyncComponent, onMounted, reactive, ref, watch } from 'vue';
import { useConfigStore } from '@renderer/stores/configStore'
import { useExPrompt } from '@renderer/stores/useExPrompt';
import { ElMessage } from 'element-plus';
import { useGenerationStore } from '@renderer/stores/useGenerationStore';
import { commonApi } from '@renderer/api/common';
import { useTranslationStore } from '@renderer/stores/useTranslationStore'
import RandomCharacter from '@renderer/views/random/component/RandomCharacter.vue';
import { ipcService } from '@renderer/services/ipcService';
defineOptions({
  name: 'RandomPanel' // 显式定义组件名称
})

interface Character {
  name: string,
  cn_name: string,
  tag: string,
  rating: number
}

interface AdjacentItemParams {
  current_id: string;
  direction: 'prev' | 'next';
  value?: number[];
  class_type: string;
}

interface AdjacentCharacterParams {
  current_name: string; // 使用名称而不是ID
  direction: 'prev' | 'next';
  rating?: number[];
}

interface PromptItem {
  id: string;
  class_type: string;
  name: string;
  customize_name: string;
  image?: string;
  tags?: string;
  description?: string;
  rating: number;
  favorite: boolean;
  disliked: boolean;
  created_at: string;
  updated_at: string;
}

const RandomTagGenerator = defineAsyncComponent(
  () => import("./component/RandomTag.vue")
);

const LoraLoader = defineAsyncComponent(() => import("./component/LoraLoader.vue"))
const translationStore = useTranslationStore()
const generationStore = useGenerationStore()
const configStore = useConfigStore()
const exPromptStore = useExPrompt()
const myOptions = reactive({
  characterRate: [0, 0]
})

const selectedCharacters = ref<string[]>([]);
const characterOptions = ref<Character[]>([]);

const state = reactive({
  style: computed({
    get: () => exPromptStore.style,
    set: (value) => exPromptStore.updateState({ style: value })
  }),
  collect: computed({
    get: () => exPromptStore.collect,
    set: (value) => exPromptStore.updateState({ collect: value })
  }),
  action: computed({
    get: () => exPromptStore.action,
    set: (value) => exPromptStore.updateState({ action: value })
  }),
  random: {
    style: {
      class_type: 'style',
      value: [0, 0],
      favorite: null as boolean | null,
      disliked: null as boolean | null,
      min_rating: 0 as number | null,
      max_rating: 0 as number | null,
    },
    collect: {
      class_type: 'collect',
      value: [0, 0],
      favorite: null as boolean | null,
      disliked: null as boolean | null,
      min_rating: 0 as number | null,
      max_rating: 0 as number | null,
    },
    action: {
      class_type: 'action',
      value: [0, 0],
      favorite: null as boolean | null,
      disliked: null as boolean | null,
      min_rating: 0 as number | null,
      max_rating: 0 as number | null,
    }
  },
});

const getCommonRandom = async (type: 'style' | 'collect' | 'action') => {
  const search = state.random[type]
  const res = await commonApi().getRandomChioce(search);

  const result = res.data.result;
  const tags = result.tags.split('Negative prompt')[0];

  exPromptStore.updateState({
    [type]: {
      ...result,
      tags,
      search
    }
  });
};

const getAdjacentPromptItem = async (type: 'style' | 'collect' | 'action', params: AdjacentItemParams) => {
  try {
    // 调用相邻记录API
    const response = await commonApi().getAdjacentPromptItem(params);

    if (!response.data.result) {
      console.warn(`No adjacent ${type} prompt found`);
      return null;
    }

    const result: PromptItem = response.data.result;

    // 处理tags（保留原有逻辑）
    const tags = result.tags ? result.tags.split('Negative prompt')[0] : '';

    // 更新状态（保留搜索条件）
    exPromptStore.updateState({
      [type]: {
        ...result,
        tags,
      }
    });

    return result;
  } catch (error) {
    console.error(`Error fetching adjacent ${type} prompt:`, error);
    return null;
  }
};

// 使用示例 - 在UI按钮事件中调用
const handlePrevItem = async (id: string, type: 'style' | 'collect' | 'action') => {
  const search = state.random[type].value
  await getAdjacentPromptItem(type, {
    current_id: id,
    direction: 'prev',
    value: search,
    class_type: type,
  });
};

const handleNextItem = async (id: string, type: 'style' | 'collect' | 'action') => {
  const search = state.random[type].value
  await getAdjacentPromptItem(type, {
    current_id: id,
    direction: 'next',
    value: search,
    class_type: type,
  });
};

const handleClear = (type: 'style' | 'collect' | 'action') => {
  exPromptStore.clearType(type);
};

const handleMoreAction = (type: 'style' | 'collect' | 'action', action: string) => {
  const item = exPromptStore[type];

  switch (action) {
    case 'copy':
      handleCopy(item.tags);
      break;
    case 'update-image':
      handleUpdatePromptImage(item);
      break;
    case 'update-item':
      handleUpdatePromptItem(item);
      break;
  }
};

const emit = defineEmits(['loadCharacters', 'loadActions', 'loadCollects', 'loadStyles']);


const handleUpdatePromptImage = async (promptItem: any) => {
  const webpData = await configStore.convertToWebpV2(generationStore.previewImage)
  try {
    const result = await ipcService.saveBase64Image({
      base64Data: webpData,
      directory: 'collections',
      fileName: `${promptItem.id}.webp`,
      imagesPath: configStore.config.imagesPath
    });

    if (result.success) {
      ElMessage.success('图片保存成功');
    } else {
      ElMessage.warning('图片保存失败，但记录已创建');
    }
  } catch (error) {
    ElMessage.error(`图片保存失败: ${error.message}`);
  }
}

const handleUpdatePromptItem = (promptItem: any) => {
  commonApi().updatePromptItem(promptItem).then((res) => {
    ElMessage.info(JSON.stringify(res.data));
  })
}

const getProcessedImageUrl = (item: any) => {
  return configStore.comfyProxyImage(`file://${configStore.config.imagesPath}\\collections\\${item.id}.webp`)
}

const handleCopy = async (content: string) => {
  try {
    await navigator.clipboard.writeText(content)
    ElMessage.success('标签已复制到剪贴板')
  } catch (err) {
    ElMessage.error('复制失败，请检查权限')
  }
}

const handleRandomTagsGenerated = (value: string) => {
  exPromptStore.setRandomTag(value);
};


watch(
  () => [...selectedCharacters.value],
  (newCharacterNames) => {
    if (newCharacterNames.length > 0) {
      const tags = newCharacterNames
        .map(name => {
          const character = characterOptions.value.find(c => c.name === name);
          return character ? character.tag : null;
        })
        .filter(tag => tag) // 过滤空标签
        .join(',');
      exPromptStore.setCharacterTag(tags);
    } else {
      exPromptStore.setCharacterTag('');
    }
  }
);

const getCharacterOptionList = () => {
  commonApi().getCharacterList().then(res => {
    characterOptions.value = res.data.data
  });
}

const getAdjacentCharacter = async (params: AdjacentCharacterParams) => {
  try {
    const response = await commonApi().getAdjacentCharacter(params);
    if (!response.data.result) {
      ElMessage.error('未找到相邻人物记录');
      return null;
    }
    return response.data.result as Character;
  } catch (error) {
    ElMessage.error('获取相邻人物记录时出错:' + JSON.stringify(error));
    return null;
  }
};

const handlePrevCharacter = async () => {
  let currentName = '';
  if (selectedCharacters.value.length === 1) {
    currentName = selectedCharacters.value[0];
  }
  const newCharacter = await getAdjacentCharacter({
    current_name: currentName,
    direction: 'prev',
    rating: myOptions.characterRate
  });

  if (newCharacter) {
    // 将新角色对象添加到characterOptions（如果不存在）
    const existingIndex = characterOptions.value.findIndex(c => c.name === newCharacter.name);
    if (existingIndex === -1) {
      characterOptions.value.push(newCharacter);
    }
    // 设置当前选中为新角色的名称
    selectedCharacters.value = [newCharacter.name];
  }
};

onMounted(() => {
  getCharacterOptionList()
})

</script>

<style lang="scss" scoped>
.random-panel {
  padding: 20px;
  background: var(--el-fill-color-lighter);

  .main-content {
    padding-right: 20px;
  }

  .panel-card {
    margin-bottom: 20px;
    border-radius: 12px;
    box-shadow: var(--el-box-shadow-light);

    :deep(.el-card__header) {
      background: linear-gradient(145deg, var(--el-fill-color-lighter), var(--el-fill-color));
      border-bottom: none;
      padding: 16px 20px;
    }

    .card-header {
      display: flex;

      .el-text {
        white-space: nowrap;
        color: var(--el-text-color-primary);
        font-size: 16px;
      }
    }
  }

  .full-width-select {
    width: 100%;
  }

  .image-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 10px;

    .preview-image {
      width: 100%;
      height: 120px;
      border-radius: 8px;
      transition: transform 0.2s;
      border: 1px solid var(--el-border-color);

      &:hover {
        transform: scale(1.03);
      }
    }
  }

  .content-wrapper {
    display: grid;
    grid-template-columns: 100px 1fr;
    gap: 15px;

    .preview-image-lg {
      width: 100px;
      border-radius: 8px;
      transition: all 0.3s ease;
      object-fit: contain;
      border: 1px solid var(--el-border-color);
    }

    .tag-input {
      height: 100%;

      :deep(textarea) {
        font-family: 'JetBrains Mono', monospace;
        font-size: 12px;
        background-color: var(--el-fill-color-lighter);
        color: var(--el-text-color-regular);
      }
    }
  }

  @media (max-width: 768px) {
    .main-content {
      padding-right: 0;
      margin-bottom: 20px;
    }

    .content-wrapper {
      grid-template-columns: 1fr;
    }
  }
}

.generate-btn,
.batch-btn {
  padding: 10px 24px;
  border-radius: 10px;
  font-weight: 500;
  transition: all 0.2s ease;
}

.prompt-content {
  font-size: 14px;
  line-height: 1.6;
  white-space: pre-wrap;
  color: var(--el-text-color-regular);
  word-break: break-all;
  overflow: hidden;
  padding: 8px;
  background-color: var(--el-fill-color-lighter);
  border-radius: 4px;
  border: 1px solid var(--el-border-color-lighter);
}

.range-btn{
  min-width: 70px;
}
</style>
